package services

import (
	"k8sdev/pkg/client"
	"log"
	"time"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/informers"
)

var (
	sif informers.SharedInformerFactory
)

func NewSIF(stopCh <-chan struct{}) (err error) {
	// 1.加载客户端
	err = client.NewClient()
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	client := client.GetClientSet()

	// 2.实例化sharedInformerFactory
	// 使用CilentSet客户端
	sif = informers.NewSharedInformerFactory(client, time.Second*60)

	// 3.informer
	gvrs := []schema.GroupVersionResource{
		{Group: "", Version: "v1", Resource: "namespaces"},
		{Group: "", Version: "v1", Resource: "pods"},
		{Group: "", Version: "v1", Resource: "nodes"},
		{Group: "apps", Version: "v1", Resource: "deployments"},
		// {Group: "install.istio.io", Version: "v1alpha1", Resource: "IstioOperator"},
	}
	for _, v := range gvrs {
		// 创建informer
		_, err = sif.ForResource(v)
		if err != nil {
			log.Fatal(err.Error())
			return
		}
	}
	//启动所有informer
	sif.Start(stopCh)

	//等待所有informer全量同步完成
	sif.WaitForCacheSync(stopCh)

	return
}

func GetSif() informers.SharedInformerFactory {
	return sif
}
